"use client";

import useBasket from "@/app/hooks/basket.hook";
import { useNotifications } from "@/app/hooks/notification.hook";
import ordersService from "@/app/services/orders.service";
import userService from "@/app/services/user.service";
import { GATEWAY_URL } from "@/lib/env";
import Item from "@/shared/item";
import User from "@/shared/user";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

export default function ArrangePage() {
  const router = useRouter();

  const { showError } = useNotifications();
  const { selected, findQuantity, clearBucket } = useBasket();
  const [items, setItems] = useState<Item[]>([]);
  const [user, setUser] = useState<User | null>(null);

  const [address, setAddress] = useState<string>("");
  const [description, setDescription] = useState<string>("");
  const [count, setCount] = useState<number>(1);

  useEffect(() => {
    userService.getMe().then((user) => {
      setUser(user);
    });
  }, []);

  useEffect(() => {
    const loading = async () => {
      const data = await getItems();

      setItems(data);
    };

    loading();
  }, [selected]);

  const getItems = async () => {
    try {
      const ids = selected.map((i) => i.itemId);
      const response = await fetch(`${GATEWAY_URL}/items/ids`, {
        method: "POST",
        body: JSON.stringify({ ids }),
        headers: {
          "Content-Type": "application/json",
        },
      });
      const data = await response.json();
      return data;
    } catch (error) {
      console.error(error);
      return [];
    }
  };

  function handleChange(e: React.FormEvent<HTMLInputElement>) {
    switch (e.target.name) {
      case "address":
        setAddress(e.target.value);
        break;
      case "description":
        setDescription(e.target.value);
        break;
      case "count":
        setCount(Number.parseInt(e.target.value));
        break;
      default:
        return;
    }
  }

  const onClickArrange = async () => {
    if (address.trim().length < 1) {
      showError("Введите адрес доставки");
      return;
    }
    try {
      const _ = await ordersService.createOrder(
        selected.map((i) => ({ id: i.itemId, quantity: i.quantity })),
        address,
        count,
        description
      );

      clearBucket();
      router.push("/arrange/success");
    } catch (error) {
      showError("Ошибка при создании заказа, повторите позже");
      return;
    }
  };

  if (selected.length < 1)
    return (
      <section className="arrange" id="arrange">
        <h1 className="heading">
          Невозможно оформить заказ, <span>корзина пустая</span>
        </h1>
      </section>
    );

  return (
    <section className="arrange" style={{ flex: 2 }} id="arrange">
      <h1 className="heading">
        Оформление <span>заказа</span>
      </h1>
      <div className="content">
        <div className="row">
          <div>
            <h1 className="colored">Адресс доставки *</h1>
            <div className="inputBox">
              <span className="fa fa-map-marker "></span>
              <input
                value={address}
                type="text"
                name="address"
                placeholder="Адрес доставки"
                onChange={handleChange}
              />
            </div>
          </div>
          <div>
            <h1 className="colored">Имя:</h1>
            <div className="inputBox" style={{ backgroundColor: "#715e48" }}>
              <span className="fas fa-info-circle "></span>
              <input type="text" disabled value={user?.name} />
            </div>
          </div>
        </div>
        <div>
          <h1 className="colored">Особые пожелания</h1>
          <div className="inputBox">
            <span className="fa fa-smile-o"></span>
            <input
              onChange={handleChange}
              name="description"
              value={description}
              type="text"
              placeholder="Особые пожелания"
            />
          </div>
        </div>
        <div className="row">
          <div className="smallInput">
            <h1 className="colored">Кол-во персон:</h1>
            <div className="inputBox">
              <span className="fas  fa-users"></span>
              <input
                type="number"
                value={count}
                onChange={handleChange}
                name="count"
              />
            </div>
          </div>
          <div className="smallInput">
            <h1 className="colored">Кол-во блюд:</h1>
            <div style={{ backgroundColor: "#715e48" }} className="inputBox">
              <span className="fas  fa-coffee"></span>
              <input
                type="text"
                disabled
                value={items.reduce((accum, _) => accum + 1, 0)}
              />
            </div>
          </div>
          <div className="smallInput">
            <h1 className="colored">Сумма:</h1>
            <div style={{ backgroundColor: "#715e48" }} className="inputBox">
              <span className="fa fa-usd"></span>
              <input
                type="text"
                disabled
                value={`${items.reduce(
                  (accum, current) =>
                    accum +
                    Number.parseFloat(current.price) *
                      (findQuantity(current.id) ?? 1),
                  0
                )} ₽`}
              />
            </div>
          </div>
        </div>

        <input
          style={{
            width: "50%",
            margin: "10px auto",
          }}
          type="submit"
          value="Оформить"
          onClick={() => onClickArrange()}
          className="btn"
        />
      </div>
    </section>
  );
}
